package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            return new CommonResult(200, "插入成功   serverPort:" + serverPort, result);
        }
        return new CommonResult(444, "插入失败", result);
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult selectPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.selectPaymentById(id);
        if (payment != null) {
            return new CommonResult(200, "查询成功   serverPort:" + serverPort, payment);
        }
        return new CommonResult(444, "查询失败,查询的id为" + id);

    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println("service = " + service);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-provider-service");
        for (ServiceInstance instance : instances) {
            System.out.println("instance = " + instance.getServiceId() + instance.getHost() + instance.getUri());
        }
        return discoveryClient;
    }

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB() {
        return serverPort;
    }


    @GetMapping("/payment/feign/timeout")
    public CommonResult timeout() throws InterruptedException {
        Thread.sleep(3000);
        return null;
    }

    @GetMapping(value = "/payment/zipkin")
    public String zipkin() {
        return "hi,i`am paymentzipkin server fall back.welcome to atguigu.hahahahahhahahah";
    }


}
